<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div v-loading="loading" element-loading-text="数据统计中..." class="data-analysis flex flex-wrap">
    <div class="top">
      <div>
        <el-select
          v-model="queryParams.scenarioId"
          size="small"
          style="width: 200px"
          placeholder="全部场景"
          clearable
          @change="handleScenarioSelectChange"
        >
          <el-option v-for="item in treeData" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
        <el-select
          v-model="queryParams.systemId"
          size="small"
          style="width: 200px; margin-left: 20px"
          :placeholder="selectList.length > 0 ? '该场景下全部业务系统' : queryParams.scenarioId ? '暂无业务系统' : '全部系统'"
          clearable
          @change="handleSelectChange"
        >
          <el-option v-for="item in selectList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </div>
      <el-button type="primary" size="small" @click="exportList()">生成报表</el-button>
    </div>
    <div class="middle">
      <div class="middle-left">
        <pieChart :pie-data="pieData" :bar-data="barData" :total="total" />
      </div>
      <div class="middle-right">
        <div class="right-top">
          <storagePie :storage="storage" />
        </div>
        <div class="right-bottom">
          <normalPieChart :normal-pie-chart-data="normalPieChartData" />
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="left">
        <div class="left-top">
          <div style="height: 15%; display: flex; align-items: center; justify-content: space-between">
            <div style="display: flex; align-items: center; justify-content: space-between">
              <div style="margin: 0px 15px; font-size: 1rem">数据增长趋势</div>
              <el-switch v-model="switchValue" size="small" active-text="默认" style="margin-left: 14px" @change="handleSwitchChange" />
            </div>
            <div>
              <el-date-picker
                v-model="dateRangeCreateTime"
                type="daterange"
                size="small"
                style="width: 200px; margin-right: 20px"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :disabled-date="pickerOptions"
                @calendar-change="pickData"
              ></el-date-picker>

              <el-button type="primary" size="small" @click="handleQuery()">查询</el-button>
              <el-button size="small" @click="handleReset()">重置</el-button>
            </div>
          </div>
          <LineChart :line-data="lineData" />
        </div>
        <div class="left-bottom">
          <VerticalBar :count-data="countData" />
        </div>
      </div>
      <div class="right">
        <div style="margin: 0px 15px; font-size: 1rem">数据服务统计</div>
        <div class="rights-top">
          <StatisticItem title="累计调用数据总量" :count="`${serviceData}条`">
            <template #default>
              <img :src="times" alt="" style="height: 2.5rem; width: 2.5rem" />
            </template>
          </StatisticItem>
        </div>
        <div class="rights-bottom">
          <dataServiceChart :service-count-data="serviceCountData" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import times from '@/assets/images/times.png';
import StatisticItem from './components/StatisticItem';
import dataServiceChart from './components/dataServiceChart';
import pieChart from './components/Pie';
import normalPieChart from './components/normalPie';
import LineChart from './components/Line';
import VerticalBar from './components/VerticalBar';
import storagePie from './components/storagePie';
import { listData } from '@/api/system/dict/data';
import {
  getCountDataByScenario,
  getDataAssetStatistics,
  getDataServiceCount,
  getDataSourceDistribution,
  getGrowthTrend,
  downLoadWord
} from '@/api/dataAnalysis';
import { getTreeList } from '@/api/businessSystem';
import { ref, onMounted } from 'vue';

const treeData = ref([]);
const selectList = ref([]);
const queryParams = ref({
  scenarioId: '',
  systemId: '',
  startTime: '',
  endTime: '',
  defaultSelect: ''
});
const subqueryParams = ref({
  scenarioId: '',
  systemId: '',
  startTime: '',
  endTime: '',
  defaultSelect: ''
});
const pieData = ref([]);
const barData = ref([]);
const total = ref([]);
const normalPieChartData = ref([]);
const lineData = ref([]);
const countData = ref([]);
const serviceData = ref('');
const serviceCountData = ref([]);
const switchValue = ref(false);
const dateRangeCreateTime = ref(['', '']);
const rangeTime = ref(['']);
const storage = ref('');
const loading = ref(false);
const handleSwitchChange = () => {
  const growthTrendParams = switchValue.value
    ? { ...subqueryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] }
    : { ...queryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] };
  getGrowthTrend(growthTrendParams).then((res) => {
    lineData.value = res.data;
  });
};

const pickData = (data) => {
  if (data[0] !== null && data[1] === null) {
    rangeTime.value = data[0];
  } else if (data[0] !== null && data[1] !== null) {
    rangeTime.value = '';
  }
  console.log('pickData', data);
};
const pickerOptions = (time) => {
  const t = new Date(time).setHours(0, 0, 0, 0);
  if (rangeTime.value) {
    const maxDate = new Date(rangeTime.value);
    const minDate = new Date(rangeTime.value);
    maxDate.setFullYear(maxDate.getFullYear() + 3);
    minDate.setFullYear(minDate.getFullYear() - 3);
    return t < minDate.getTime() || t > maxDate.getTime();
  }
};

const handleQuery = () => {
  const growthTrendParams = switchValue.value
    ? { ...subqueryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] }
    : { ...queryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] };
  getGrowthTrend(growthTrendParams).then((res) => {
    lineData.value = res.data;
  });
};

const handleReset = () => {
  dateRangeCreateTime.value = ['', ''];
  handleQuery();
};

const handleScenarioSelectChange = (data) => {
  queryParams.value.systemId = '';
  const matchedItem = treeData.value.find((item) => item.id === data);
  selectList.value = matchedItem?.children || [];
  getList();
};

const handleSelectChange = () => {
  getList();
};

const exportList = () => {
  const growthTrendParams = switchValue.value
    ? { ...subqueryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] }
    : { ...queryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] };
  downLoadWord(growthTrendParams).then((response) => {
    // 创建临时下载链接
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' // Word MIME类型 :ml-citation{ref="4,11" data="citationList"}
    });
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = '统计分析报表';
    document.body.appendChild(a);
    a.click();
  });
};

const getList = async () => {
  loading.value = true;
  const growthTrendParams = switchValue.value
    ? { ...subqueryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] }
    : { ...queryParams.value, startTime: dateRangeCreateTime.value[0], endTime: dateRangeCreateTime.value[1] };
  try {
    const [countDataRes, getDataAssetStatisticsRes, getDataServiceCountRes, getDataSourceDistributionRes, listDataRes, getGrowthTrendRes] =
      await Promise.all([
        getCountDataByScenario(queryParams.value),
        getDataAssetStatistics(queryParams.value),
        getDataServiceCount(queryParams.value),
        getDataSourceDistribution(queryParams.value),
        listData({ pageNum: 1, pageSize: 10, dictType: 'storage_space' }),
        getGrowthTrend(growthTrendParams)
      ]);
    countData.value = countDataRes.data;
    pieData.value = getDataAssetStatisticsRes.data.dataAssetList;
    barData.value = getDataAssetStatisticsRes.data.staticAssetList;
    total.value = getDataAssetStatisticsRes.data.totalCount || 0;
    serviceData.value = getDataServiceCountRes.data.dataTotalCount || 0;
    serviceCountData.value = getDataServiceCountRes.data;
    normalPieChartData.value = getDataSourceDistributionRes.data.dataSourceDistribution;
    storage.value = listDataRes.rows[0].dictValue || '0';
    lineData.value = getGrowthTrendRes.data;
  } catch (error) {
    console.error('获取数据时出错:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getTreeList({ name: '' }).then((res) => {
    if (res) {
      treeData.value = res || [];
    }
  });
  getList();
});
</script>

<style lang="scss" scoped>
.data-analysis {
  width: 100%;
  height: calc(100vh - 84px);
  background: rgba(247, 249, 252, 1);
  padding: 5px 10px;
  overflow: hidden;
  .top {
    width: 100%;
    padding: 0px 0px 5px 0px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .middle {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 41%;
    .middle-left {
      width: calc(60% - 10px);
      height: 100%;
    }
    .middle-right {
      width: 40%;
      .right-top {
        width: 100%;
        height: calc(50% - 5px);
      }
      .right-bottom {
        width: 100%;
        height: calc(50% - 5px);
        margin-top: 10px;
      }
    }
  }
  .bottom {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 55%;
    .left {
      width: calc(60% - 10px);
      height: calc(100% - 10px);
      .left-top {
        width: 100%;
        height: calc(50% - 10px);
        margin-top: 10px;
        background: rgba(255, 255, 255, 1);
        box-shadow: 4px 4px 10px rgba(218, 218, 218, 0.5);
        border-radius: 5px;
        padding: 10px;
      }
      .left-bottom {
        width: 100%;
        height: calc(50%);
        margin-top: 10px;
      }
    }
    .right {
      width: 40%;
      height: calc(100% - 10px);
      margin-top: 10px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 4px 4px 10px rgba(218, 218, 218, 0.5);
      border-radius: 5px;
      padding: 10px;
      .rights-top {
        width: 100%;
        height: 10%;
      }
      .rights-bottom {
        width: 100%;
        height: 80%;
      }
    }
  }
}
</style>
